<?php
	require_once(dirname(__FILE__)."/session_auth.php");
	// we don't have to update $_SESSION
	session_write_close();
?>
<?php
	require_once(dirname(__FILE__)."/config.php");
	require_once(dirname(__FILE__)."/class/server/ServerDao.php");
	require_once(dirname(__FILE__)."/class/server/ServerListTypeDao.php");
	require_once(dirname(__FILE__)."/response.php");
	function removeServerDaoPassword(&$newslist,$slist)
	{
		//remove password
		foreach($slist as $server)
		{
			$temp=&$server['hostinfo'];
            if(isset($temp['customFields']['password']) && is_array($temp['customFields']['password']))
            {
                foreach($temp['customFields']['password'] as $key=>$value)
                {
					if ($temp['customFields']['password'][$key] != ''){
						$temp['customFields']['password'][$key]='*****';
					}                    
                }
            }
            //settype is because
            //if $temp = "{'a','b'}";
            //use $temp['password'] will get "{"
            //will cause error
            //so use settype to change $temp tostring
            if(is_string($temp)){
                settype($temp,'string');
            }

			if(isset($temp['password']))
			{
				if ($temp['password'] != ''){
					$temp['password']= '*****';
				}
				$newslist[]=$server;
			}
			else{
				$newslist[]=$server;
			}
		}
	}
    function removeServerListTypeCustomPassword(&$newstypelist,$stypelist)
    {
        foreach($stypelist as $stype)
        {
            if($stype['customFields'])
            {
                $customFields=json_decode($stype['customFields'],true);
                foreach($customFields as $key=>$item)
                {
                    if ($item['type']==='password')
                    {
						if ($customFields[$key]['value'] != ''){
							$customFields[$key]['value'] 	= '*****';
						}else{
                        	$customFields[$key]['value']='';
						}
                    }
                }
                $stype['customFields']=json_encode($customFields);
            }
            $newstypelist[]=$stype;
        }
    }
?>
<?php
/*
 * Server List
 * Created: 200904 (TT Tsai)
 */

	// load data from POST string
	$widgetRequest = json_decode($HTTP_RAW_POST_DATA,true);
	if( $widgetRequest == null ) {
		// input format error
		make_error_response( SLIST_ERRCODE_INVALIDFORMAT, SLIST_ERRCODE_INVALIDFORMAT_MSG);
		exit;
	}

	// check act
	if( !isset($widgetRequest["act"]) ) {
		// we can do nothing without 'act'
		make_error_response( SLIST_ERRCODE_NOACT, SLIST_ERRCODE_NOACT_MSG);
		exit;
	}

	// userid
	if( !isset($_SESSION['uid']) ) {
		make_error_response( SLIST_ERRCODE_WFERR, SLIST_ERRCODE_WFERR_MSG.": retrieving userid failed");
		exit;
	}
	$userid = $_SESSION['uid'];

	// create ServerList object
	$slistobj = new WFServerDao( $wfconf_dbconfig, $userid);
	if( $slistobj->isFailed() ) {
		make_error_response( SLIST_ERRCODE_DBINIT, SLIST_ERRCODE_DBINIT_MSG.": ".$slistobj->getErrMessage());
		exit;
	}
	// create ServerListType object
	$slisttypeobj = new WFServerListTypeDao( $wfconf_dbconfig);
	if( $slisttypeobj->isFailed() ) {
		make_error_response( SLIST_ERRCODE_DBINIT, SLIST_ERRCODE_DBINIT_MSG.": ".$slisttypeobj->getErrMessage());
		exit;
	}
	switch($widgetRequest['act']) {
	case "add":
		// check parameters
		if( !isset($widgetRequest["name"]) || !isset($widgetRequest["serverinfo"]) ) {
			make_error_response( SLIST_ERRCODE_LACKINPUT, SLIST_ERRCODE_LACKINPUT_MSG);
			exit;
		}

		if(isset($widgetRequest["defaultPasswordFields"]) && $widgetRequest["defaultPasswordFields"] != ''){
			$defaultPasswordFields = explode(",",$widgetRequest["defaultPasswordFields"]);
			$stypelist =$slisttypeobj->getall();
			foreach($stypelist as $stype){
				if($widgetRequest["serverinfo"]["type"] === $stype["type"]){
				    foreach($defaultPasswordFields as $defaultPasswordField){
                    	$customFields = json_decode($stype['customFields'],true);
						foreach($customFields as $key => $value) {
						    if ($value['type'] === 'password' && $defaultPasswordField === $value['name']){
							    $arrDefaultPasswords[$defaultPasswordField] = $value['value'];
								break;
							}
						}
					}
					break;
				}
			}
		}

		// add
		$slistobj->add( $widgetRequest["name"], $widgetRequest["serverinfo"], $arrDefaultPasswords);
		if( $slistobj->isFailed() ) {
			make_error_response( SLIST_ERRCODE_DBERR, SLIST_ERRCODE_DBERR_MSG.": ".$slistobj->getErrMessage());
			exit;
		}
		// get the id of the host
		$hostid = $slistobj->getlastid();
		make_successful_response( SLIST_OK_ADD_MSG, $hostid);
		break;
	case "delete":
		// check parameters
		if( !isset($widgetRequest["serverid"]) ) {
			make_error_response( SLIST_ERRCODE_LACKINPUT, SLIST_ERRCODE_LACKINPUT_MSG);
			exit;
		}
		// delete
		$slistobj->del($widgetRequest["serverid"]);
		if( $slistobj->isFailed() ) {
			make_error_response( SLIST_ERRCODE_DBERR, SLIST_ERRCODE_DBERR_MSG.": ".$slistobj->getErrMessage());
			exit;
		}
		make_successful_response( SLIST_OK_DEL_MSG, null);
		break;
	case "batchdelete" :
		// check parameters
		if (! isset ( $widgetRequest ["serverids"] )) {
			make_error_response ( SLIST_ERRCODE_LACKINPUT, SLIST_ERRCODE_LACKINPUT_MSG );
			exit ();
		}
		// delete
		$arrServerIDs=explode(",",$widgetRequest ["serverids"]);
	    foreach($arrServerIDs as $serverID)
		{
			$slistobj->del($serverID);
			if ($slistobj->isFailed ()) {
				make_error_response ( SLIST_ERRCODE_DBERR, SLIST_ERRCODE_DBERR_MSG . ": " . $slistobj->getErrMessage () );
				exit ();
			}
		}
		make_successful_response ( SLIST_OK_DEL_MSG, null );
		break;	
	case "update":			
		// check parameters
		if( !isset($widgetRequest["serverid"]) || !isset($widgetRequest["name"]) || !isset($widgetRequest["serverinfo"]) ) {
			make_error_response( SLIST_ERRCODE_LACKINPUT, SLIST_ERRCODE_LACKINPUT_MSG);
			exit;
		}
		
		if(isset($widgetRequest["defaultPasswordFields"]) && $widgetRequest["defaultPasswordFields"] != ''){
			$defaultPasswordFields = explode(",",$widgetRequest["defaultPasswordFields"]);
			$stypelist =$slisttypeobj->getall();
			foreach($stypelist as $stype){
				if($widgetRequest["serverinfo"]["type"] === $stype["type"]){
					foreach($defaultPasswordFields as $defaultPasswordField){
                        $customFields = json_decode($stype['customFields'],true);
						foreach($customFields as $key => $value){
							if ($value['type'] === 'password' && $defaultPasswordField === $value['name']){
								$arrDefaultPasswords[$defaultPasswordField] = $value['value'];
								break;
							}
						}
					}
					break;
				}
			}
		}

		$slistobj->update( $widgetRequest["serverid"], $widgetRequest["name"], $widgetRequest["serverinfo"], $arrDefaultPasswords);
		if( $slistobj->isFailed() ) {
			make_error_response( SLIST_ERRCODE_DBERR, SLIST_ERRCODE_DBERR_MSG.": ".$slistobj->getErrMessage());
			exit;
		}
		make_successful_response( SLIST_OK_UPDATE_MSG, null);
		break;
	case "getall":
		$slist = $slistobj->getall();
		if( $slistobj->isFailed() ) {
			make_error_response( SLIST_ERRCODE_DBERR, SLIST_ERRCODE_DBERR_MSG.": ".$slistobj->getErrMessage());
			exit;
		}
		$newslist=array();
		removeServerDaoPassword($newslist,$slist);
		make_successful_response( null, $newslist);
		break;
	case "getall_serverlisttype":
		$slist = $slistobj->getall();
		if( $slistobj->isFailed() ) {
			make_error_response( SLIST_ERRCODE_DBERR, SLIST_ERRCODE_DBERR_MSG.": ".$slistobj->getErrMessage());
			exit;
		}
		$stypelist =$slisttypeobj->getall();
		$newslist=array();
        $newstypelist=array();
        
		removeServerDaoPassword($newslist,$slist);
        removeServerListTypeCustomPassword($newstypelist,$stypelist);
		$arr= array("serverlist"=>$newslist,"serverlisttype"=>$newstypelist);
		make_successful_response( null, $arr);
		break;
	case "get":
		// check parameters
		if( !isset($widgetRequest["serverid"]) ) {
			make_error_response( SLIST_ERRCODE_LACKINPUT, SLIST_ERRCODE_LACKINPUT_MSG);
			exit;
		}
		// get
		$slist = $slistobj->getinfo($widgetRequest["serverid"]);
		if( $slistobj->isFailed() ) {
			make_error_response( SLIST_ERRCODE_DBERR, SLIST_ERRCODE_DBERR_MSG.": ".$slistobj->getErrMessage());
			exit;
		}
		make_successful_response( null, $slist);
		break;
	default:
		make_error_response( SLIST_ERRCODE_CMDERR, SLIST_ERRCODE_CMDERR_MSG);
		break;
	}
?>
